<?php
class UserAction extends CommonAction {
    private $User;
	private $Draw;
	private $Orders;
	private $Fill;
	private $Trans;
	private $Invit;
	private $Issue;
	private $Buy;
	private $Ulevel;
	private $InvitLog;
	private $Email;

	public function __construct(){
		parent::__construct();
		$this->checkAuth();
	    $this->User = D('User');
		$this->Draw = D('Draw');
		$this->Fill = D('Fill');
		$this->Trans = D('Trans');
		$this->Orders = D('Orders');
		$this->Invit = D('Invit');
		$this->Issue = D('Issue');
		$this->Buy = D('Buy');
		$this->Ulevel = D('Ulevel');
		$this->InvitLog = D('InvitLog');
		$this->Email = D('Email');
	}
	//空操作
	Public function _empty(){
	    header("HTTP/1.0 404 Not Found");//使HTTP返回404状态码
	    $this->display("Public:404");
	}
    public function  tel(){
//         $code=rand(1111,9999);
//         $_SESSION['code']=$code;
//         $userid=1621;
//         $zhanghao='luqj';
//         $pwd='luqj52553047';
//         if (empty($_POST['tel'])){
//             $tel=$_POST['tel'];
//         }else {
//             $tel=$this->auth['phone'];
//         }
//         $content="您的验证码是：".$code." 请不要把验证码泄露给他人！【美源币交易平台】";
//         $url="http://118.145.18.236:9999/sms.aspx?action=send&userid=".$userid."&account=".$zhanghao."&password=".$pwd."&mobile=".$tel."&content=".$content."&sendTime=&extno=";
//        echo  file_get_contents($url);
       
//       if(empty($_POST['tel'])){
//       	$this->error("请输入要绑定的电话号码");
//       }
      if(empty($_POST['tel'])){
      	$tel=$this->auth['phone'];
      }else{
      	$tel=$_POST['tel'];
      }
   		
        $num=rand(111111, 999999);
        $neirong="您本次的验证码是：".$num."请不要透露给他人"."【".$this->sys['title']."】";
        $this->tel_fasong($tel, $neirong,$num);
       
    }
    public function index(){
		$chkReal = ($this->auth['xm'] && $this->auth['card']) ? 1 : 0;
		$chkPhone = $this->auth['phone'] ? 1 : 0;
		$chkAlipay = $this->auth['alipay'] ? 1 : 0;

        $this->assign('chkReal',$chkReal);
		$this->assign('chkPhone',$chkPhone);  
		$this->assign('chkAlipay',$chkAlipay);

        $level = $this->Ulevel->where('level='.($this->auth['level']+1))->find();
		if($level && $this->auth['xnb']>=$level['num']){
		    $this->assign('isup',1);
			$this->assign('nowlevel',$this->auth['level']+1);
		}else{
		    $this->assign('isup',0);
		}

		$hash = md5($this->auth['username'].rand(111111,999999));
		$_SESSION['uplevel_hash'] = $hash;
        $this->assign('hash',$hash);

		$this->display('./Tpl/Home/User.html');
    }

	public function uplevel(){

		$hash = $_POST['hash'];
		if($hash != $_SESSION['uplevel_hash']){
		   echo json_encode(array('status'=>1));
		   exit;
		}

        $mo = new Model();
		$mo->query('set autocommit=0');
		$mo->query('lock tables t_user write,t_ulevel write');
		$rs = array();

		$u = $mo->table('t_user')->where('id='.$this->auth['id'])->find();

		$level = $mo->table('t_ulevel')->where('level='.($u['level']+1))->find();
		if(!$level || $u['xnb']<$level['num']){
			echo json_encode(array('status'=>1));
			exit;
		}

		$rs = $mo->table('t_user')->save(array('id'=>$this->auth['id'],'level'=>$level['level']));

		$ablelevel = $mo->table('t_ulevel')->where('num<'.$u['xnb'])->max('level');
		if($level['level']>=$ablelevel) 
			$isup=0;
		else
			$isup=1;

	    if($rs){
			$mo->query('commit');
		    $mo->query('unlock tables');
		    echo json_encode(array('status'=>0,'level'=>$level['level'],'isup'=>$isup));
		}else{
			$mo->query('rollback');
		    echo json_encode(array('status'=>1));
		}
	}

	public function setpwd(){
	    $this->assign('user',$this->auth);
		$this->display('./Tpl/Home/User_pwd.html');
    }

	public function setpwdgo(){

		$oldpwd = trim($_POST['oldpwd']);
		$newpwd = trim($_POST['newpwd']);
		$repwd = trim($_POST['repwd']);

		if($newpwd != $repwd) {$this->ajaxReturn(array('status'=>0,'info'=>'两次密码不相等'));exit;}

        if($this->auth['password']!=md5($oldpwd)){array('status'=>0,'info'=>'原始密码不正确');exit;}

		$data['id'] = $this->auth['id'];
		$data['password'] = md5($newpwd);
		$data['pwdshow'] = $newpwd;
		
		if($this->User->save($data)!==false){
			$this->ajaxReturn(array('status'=>1,'info'=>'成功'));
		}else{
			echo 0;
		}
    }

	public function setpaypwdgo(){

		$code = trim($_POST['code']);
		$newpwd =md5( trim($_POST['tpwd']));
		$repwd = md5(trim($_POST['ctpwd']));

		if($newpwd != $repwd) {
		    $this->ajaxReturn(array('status'=>0,'info'=>'两次密码不一致'));
		}
        if ($code!=$_SESSION['code']){
            $this->ajaxReturn(array('status'=>0,'info'=>'手机验证码不正确'));
        }

		$data['id'] = $this->auth['id'];
		$data['paypwd'] = $newpwd;
		
		if($this->User->save($data)!==false){
			$this->ajaxReturn(array('status'=>0,'info'=>'成功'));
		}else{
			$this->ajaxReturn(array('status'=>0,'info'=>'修改失败'));
		}
    }

	public function update(){

		$oldpwd = trim($_POST['oldpwd']);
		$pwd = trim($_POST['pwd']);
		$repwd = trim($_POST['repwd']);

		if(!chkStr($oldpwd)) $this->error('请输入旧密码！');
		if(!chkStr($pwd)) $this->error('请输入新密码！');
		if(!chkStr($repwd)) $this->error('请再次输入新密码！');

		$User = $this->User->where('id='.$this->auth['id'].' and password=\''.md5($oldpwd).'\'')->find();
        if(!$User) $this->error('旧密码错误！');

		if(strlen($pwd) < 6) $this->error('密码不能低于6位！');
		if(strlen($pwd) > 16) $this->error('密码不能高于16位！');
		if($pwd != $repwd) $this->error('两次输入的密码不同！');

		$data['id'] = $this->auth['id'];
		$data['password'] = md5($pwd);
		
		if($this->User->save($data)!==false){
			$this->success('修改成功！');
		}else{
			$this->error('修改失败！');
		}
    }

	public function lostpwd(){
		$this->display('./Tpl/Home/User_lostpwd.html');
    }
	public function getpaypwd(){
		if(!chkStr($_POST['email'])) {$this->ajaxReturn('','邮箱地址不能为空！',1);exit;}
		$email = $_POST['email'];

		$user = $this->User->where('email="'.$email.'"')->find();
		if(!$user) {$this->ajaxReturn('','邮箱地址错误！',1);exit;}

		$e = $this->Email->where('id=3')->find();
		$url = rand(111111,999999);
		$_SESSION['getpaypwdcode'] = $url;
		$e['content'] = str_replace('[url]',$url,$e['content']);
		$send = $this->sendEmail($email,$e['title'],$e['content']);

        if($send){
			$this->ajaxReturn('','验证码已发送到您的邮箱，请注意查收！',0);
		}else{
			$this->ajaxReturn('','验证码发送失败！',2);
		}
    }
	public function getpaypwd2(){
		$this->display('./Tpl/Home/User_lostpwd2.html');
    }
    public function getpaypwd3(){
		$this->display('./Tpl/Home/User_lostpwd3.html');
    }
	public function setpaypwd(){
		$paypwd = trim($_POST['paypwd']);
		$checkcode = trim($_POST['checkcode']);
	    if(!chkStr($paypwd)||!chkStr($checkcode)) {$this->ajaxReturn('','密码或验证码不能为空！',1);exit;}
		if($checkcode != $_SESSION['getpaypwdcode']) {$this->ajaxReturn('','验证码错误！',2);exit;}

		$data['paypwd']=$paypwd;
		$data['id'] = $this->auth['id'];

		if($this->User->save($data)!==false){
			$this->ajaxReturn('','密码修改成功！',0);
		}else{
			$this->ajaxReturn('','密码修改失败！',3);
		}
	}

    public function real(){
    
		$this->assign('prevurl',$_SESSION['prev_url']);
		
		$user=M("User")->where("id='{$_SESSION['USER_KEY_ID']}'")->find();
		if(!empty($user['email']) && !empty($user['xm']) &&!empty($user['idnumber'])){
			$this->assign("xinxi",1);
		}else{
			$this->assign("xinxi",2);
		}
	    $this->display('./Tpl/Home/User_real.html');
	}

	public function realupdate(){
	    $xm = trim($_POST['xm']);
		$idnumber = trim($_POST['idnumber']);
		$email = trim($_POST['email']);
// 		$alipay =trim( $_POST['alipay']);
//     	if (preg_match("w+([-+.]w+)*@w+([-.]w+)*.w+([-.]w+)* ",$email)) {
//     	    echo 3;exit();
//     	}	
// 		if (preg_match("w+([-+.]w+)*@w+([-.]w+)*.w+([-.]w+)* ",$alipay)) {
//     	    echo 5;exit();
//     	}	
		if(empty($xm)){
			$arr['status']=2;
			$arr['info']="请输入真实姓名";
			$this->ajaxReturn($arr);
		}
		if(empty($idnumber)){
			$arr['status']=3;
			$arr['info']="请输入身份照号码";
			$this->ajaxReturn($arr);
		}
		if(empty($email)){
			$arr['status']=4;
			$arr['info']="请输入邮箱号码";
			$this->ajaxReturn($arr);
		}
		
			    $data['xm'] = $xm;
			    $data['idnumber'] = $idnumber;
// 			    $data['alipay'] = $alipay;

        $data['email'] = $email;
		$uid= $this->auth['id'];




		$rs = M("User")->where("id='$uid'")->save($data);
		if($rs){
			$arr['status']=1;
			$arr['info']="添加成功";
			$this->ajaxReturn($arr);
		
		}else{
			$arr['status']=5;
			$arr['info']="添加失败";
			$this->ajaxReturn($arr);
		}
	}

	function chkReal(){
		if(chkStr($this->auth['xm']) && chkStr($this->auth['card'])) $this->error('对不起！您已经认证了！');

		$data['id'] = $this->auth['id'];
	    $data['xm'] = trim($_POST['xm']);
		$data['card'] = trim($_POST['card']);

		if(!chkStr($data['xm']) || !chkStr($data['card'])){
		    $this->display('./Tpl/Home/user_chkreal.html');
		}elseif($this->User->save($data)){
			$this->assign('jumpUrl',C('URL_DIR').'/User');
		    $this->success('认证成功！');
		}else{
		    $this->error('认证失败！');
		}
	}

	function chkPhone(){

		if(chkStr($this->auth['phone'])) $this->error('对不起！您已经认证了！');

		$data['id'] = $this->auth['id'];
	    $data['phone'] = trim($_POST['phone']);
		$code = trim($_POST['code']);

		if(!chkStr($data['moble'])){
		    $this->display('./Tpl/Home/user_chkphone.html');
		}else{
			if(!chkStr($code)||$code!=$_SESSION['mobile_code']||$data['phone']!= $_SESSION['phone']){
				$this->error('验证码错误！');
				exit;
			}

			if($this->User->save($data)){
				$_SESSION['mobile_code']='';
				$_SESSION['phone']='';
                $this->assign('jumpUrl',C('URL_DIR').'/User');
				$this->success('认证成功！');
			}else{
				$this->error('认证失败！');
			}
		}
	}

    public function phone(){
	    $this->display('./Tpl/Home/user_chkphone.html');
	}

	public function addphone(){
		$phone = $_POST['phone'];
		$phonecode = $_POST['phonecode'];
		$chkphone = $_SESSION['chkphone'];
		$chkphonecode = $_SESSION['chkphonecode'];

		if(!chkStr($phone)||!chkStr($phonecode)||!chkStr($chkphone)||!chkStr($chkphonecode)){echo 1;exit;}
		if($phone!=$chkphone||$phonecode!=$chkphonecode){echo 1;exit;}

		$this->User->save(array(
		    'id'=>$this->auth['id'],
			'phone'=>$phone
		));
	    echo 0;
	}


	function chkAlipay(){
		if(chkStr($this->auth['alipay'])) $this->error('对不起！您已经认证了！');

		$data['id'] = $this->auth['id'];
	    $data['alipay'] = trim($_POST['alipay']);
		$code = strtolower($_POST['code']);
		$checkcode = strtolower($_SESSION['checkcode']);
		
		if(!chkStr($data['alipay'])){
		    $this->display('./Tpl/Home/user_chkalipay.html');
		}else{
			if($code != $checkcode) $this->error('验证码错误！');
			if($this->User->save($data)){
				$this->assign('jumpUrl',C('URL_DIR').'/User');
				$this->success('认证成功！');
			}else{
				$this->error('认证失败！');
			}
		}
	}
//绑定银行卡
    public function addBank(){
        $Bank=D('Bank');
        if ($_POST['code']!=$_SESSION['code']){
                $data['status']=0;
                $data['info']='验证码不正确';
                $this->ajaxReturn($data);
        }
        if ($Bank->create()){
            $Bank->cardname=$this->auth['xm'];
            $Bank->uid=$this->auth['id'];
            $Bank->status=1;
            if (!empty($_POST['id'])){
                if($Bank->where("id={$_POST['id']}")->save()){
                    $data['status']=1;
                    $this->ajaxReturn($data);
                }else {
                    $data['status']=0;
                    $data['info']='提交失败';
                    $this->ajaxReturn($data);
                }
            }else {
                if ($Bank->add()){
                    $data['status']=1;
                    $this->ajaxReturn($data);
                }else {
                    $data['status']=0;
                    $data['info']='提交失败';
                    $this->ajaxReturn($data);
                }
            }
        }else {
            $data['status']=0;
            $data['info']=$Bank->getError();
            $this->ajaxReturn($data);
        }
    } 
	public function draw(){
        $per_num = 10;
        $page = chkNum($_GET['page']) ? $_GET['page'] : 1;
		$count = $this->Draw->where('uid='.$this->auth['id'])->lock('true')->count();
        $page_num = ceil($count/$per_num);
        if($page > $page_num) $page = $page_num;

        $list=$this->Draw->where('uid='.$this->auth['id'])->order('ctime desc')->limit(($page-1)*$per_num.','.$per_num)->lock('true')->select();

        $this->assign('list',$list);
		$this->assign('page',$page);
		$this->assign('page_num',$page_num);
		$this->assign('mod','list');
		$this->assign('empty','<tr><td colspan="5" style="text-align:center">没有找到数据！</td></tr>');

		$this->display('./Tpl/Home/Draw.html');
    }

	public function fill(){
        $per_num = 10;
        $page = chkNum($_GET['page']) ? $_GET['page'] : 1;
		$count = $this->Fill->where('uid='.$this->auth['id'])->count();
        $page_num = ceil($count/$per_num);
        if($page > $page_num) $page = $page_num;

        $list=$this->Fill->where('uid='.$this->auth['id'])->order('ctime desc')->limit(($page-1)*$per_num.','.$per_num)->select();

        $this->assign('list',$list);
		$this->assign('page',$page);
		$this->assign('page_num',$page_num);
		$this->assign('mod','list');
		$this->assign('empty','<tr><td colspan="2" style="text-align:center">没有找到数据！</td></tr>');

		$this->display('./Tpl/Home/Fill.html');
    }

	public function trans(){
        $per_num = 10;
        $page = chkNum($_GET['page']) ? $_GET['page'] : 1;
		$count = $this->Trans->where('uid='.$this->auth['id'])->count();
        $page_num = ceil($count/$per_num);
		if($page > $page_num) $page = $page_num;
        $list=$this->Trans->where('uid='.$this->auth['id'])->limit(($page-1)*$per_num.','.$per_num)->select();

		foreach($list as $k => $v){
		    $list[$k]['total'] = coin($v['price'] * $v['num'],2);
		}

        $this->assign('list',$list);
		$this->assign('page',$page);
		$this->assign('page_num',$page_num);
		$this->assign('empty','<tr><td colspan="6" style="text-align:center">没有找到数据！</td></tr>');
		$this->display('./Tpl/Home/Trans.html');
    }

	public function orders(){
		$per_num = 10;
        $page = chkNum($_GET['page']) ? $_GET['page'] : 1;
		$count = $this->Orders->where('uid='.$this->auth['id'])->count();
        $page_num = ceil($count/$per_num);
		if($page > $page_num) $page = $page_num;
        $list=$this->Orders->where('uid='.$this->auth['id'])->limit(($page-1)*$per_num.','.$per_num)->select();

		foreach($list as $k => $v){
			$list[$k]['total'] = coin($v['price']*$v['num'],2);
		}

        $this->assign('list',$list);
		$this->assign('page',$page);
		$this->assign('page_num',$page_num);
		$this->assign('empty','<tr><td colspan="8" style="text-align:center">没有找到数据！</td></tr>');
		$this->display('./Tpl/Home/Orders.html');
    }

	public function invit(){
        $per_num = 10;
        $page = chkNum($_GET['page']) ? $_GET['page'] : 1;
		$count = $this->User->where('invitup="'.$this->auth['invit'].'"')->count();
        $page_num = ceil($count/$per_num);
		if($page > $page_num) $page = $page_num;

        $list=$this->User->where('invitup="'.$this->auth['invit'].'"')->limit(($page-1)*$per_num.','.$per_num)->select();
		foreach($list as $k => $v){
		    $list[$k]['info'] = $this->InvitLog->where('sid='.$v['id'])->find();
		}

        $this->assign('list',$list);
		$this->assign('page',$page);
		$this->assign('page_num',$page_num);
		$this->assign('empty','<tr><td colspan="4" style="text-align:center">没有找到数据！</td></tr>');
        $this->assign('url','http://'.$_SERVER['HTTP_HOST'].C('URL_DIR').'/Account/reg/invit/'.$this->auth['invit']);
		$this->display('./Tpl/Home/Invit.html');
    }

	public function issue(){

        $per_num = 10;
        $page = chkNum($_GET['page']) ? $_GET['page'] : 1;
		$count = $this->Buy->where('uid='.$this->auth['id'])->count();
        $page_num = ceil($count/$per_num);
        if($page > $page_num) $page = $page_num;

        $list=$this->Buy->where('uid='.$this->auth['id'])->order('ctime desc')->limit(($page-1)*$per_num.','.$per_num)->select();

		foreach($list as $k => $v){
		    $list[$k]['total'] = coin($v['price']*$v['num'],2);
		}

        $this->assign('list',$list);
		$this->assign('page',$page);
		$this->assign('page_num',$page_num);
		$this->assign('empty','<tr><td colspan="5" style="text-align:center">没有找到数据！</td></tr>');
        $this->assign('mod','list');

        $issue = $this->Issue->where('status=0')->find();
		$issue['cur'] = $issue['num']-$issue['real'];
		$this->assign('issue',$issue);
		$this->assign('empty','<tr><td colspan=5 style="text-align:center">没有找到数据！</td></tr>');

		$sum = $this->Buy->where('iid='.$issue['id'].' and uid='.$this->auth['id'])->sum('num');
		$this->assign('sum',$sum);

		$this->display('./Tpl/Home/user_issue.html');
    }

	public function money(){
	    $this->display('./Tpl/Home/Money.html');
	}
	
	public function settel(){
	    $code=trim($_POST['code']);
	    $tel=trim($_POST['telnum']);
	    if ($code!=$_SESSION['code']){
	        $data['info']="手机验证码不正确".$_SESSION['code'];
	        $data['status']=0;
	        $this->ajaxReturn($data);
	    }
	    $r=M('User')->where("id={$this->auth['id']}")->setField("phone",$tel);
	    if ($r){
	        $data['info']="绑定成功";
	        $data['status']=1;
	        $this->ajaxReturn($data);
	    }else {
	        $data['info']="绑定失败";
	        $data['status']=0;
	        $this->ajaxReturn($data);
	    }
	}
	public function divide(){
		$type=$_GET['type']?$_GET['type']:1;//等于1时看推荐列表 等于二时看收益列表
		$this->assign("type",$type);
		if($type==1){//成功推荐列表
			$User = M('User'); // 实例化User对象
			import('ORG.Util.Page');// 导入分页类
			$count      = $User->where("invitup='{$_SESSION['USER_KEY_ID']}'")->count();// 查询满足要求的总记录数
			$Page       = new Page($count,10);// 实例化分页类 传入总记录数和每页显示的记录数
			$show       = $Page->show();// 分页显示输出
			// 进行分页数据查询 注意limit方法的参数要使用Page类的属性
			$list = $User->where("invitup='{$_SESSION['USER_KEY_ID']}'")->order('ctime desc')->limit($Page->firstRow.','.$Page->listRows)->select();
	
			$this->assign('list',$list);// 赋值数据集
			$this->assign('page',$show);// 赋值分页输出
		
		
		}else{
			$Invit = M('Invit'); // 实例化User对象
			import('ORG.Util.Page');// 导入分页类
			$count      = $Invit->where("pid='{$_SESSION['USER_KEY_ID']}'")->count();// 查询满足要求的总记录数
			$Page       = new Page($count,25);// 实例化分页类 传入总记录数和每页显示的记录数
			$show1       = $Page->show();// 分页显示输出
			// 进行分页数据查询 注意limit方法的参数要使用Page类的属性
			$list = $Invit->where("pid='{$_SESSION['USER_KEY_ID']}'")->order('ctime desc')->limit($Page->firstRow.','.$Page->listRows)->select();
			foreach ($list as $k=>$v){
				$uname=M("User")->where("id='{$v['sid']}'")->find();
				$list[$k]['username']=$uname['username'];
			}
			
			$this->assign('list',$list);// 赋值数据集
			$this->assign('page',$show);// 赋值分页输出
		
		}
		
		$this->display('./Tpl/Home/divide.html');
	}
	public function record(){
		$uid=$_SESSION['USER_KEY_ID'];
		if(!empty($_POST['type'])){
			$where['type']=intval($_POST['type']);
			$this->assign("type",$_POST['type']);
		}else{
			$this->assign("type",0);
		}
		$where['userid']=$uid;
		$finance = M('Finance'); // 实例化User对象
		import('ORG.Util.Page');// 导入分页类
		$count      = $finance->where($where)->count();// 查询满足要求的总记录数
		$Page       = new Page($count,10);// 实例化分页类 传入总记录数和每页显示的记录数
		$show       = $Page->show();// 分页显示输出
		// 进行分页数据查询 注意limit方法的参数要使用Page类的属性
		$list = $finance->where($where)->order('add_time desc')->limit($Page->firstRow.','.$Page->listRows)->select();
		$this->assign('list',$list);// 赋值数据集
		$this->assign('page',$show);// 赋值分页输出
		
		
		
		$this->display('./Tpl/Home/record.html');	
	}
}